package com.application.chiettinhdienluc.utils;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Handler;
import android.os.Looper;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.application.chiettinhdienluc.R;
import com.application.chiettinhdienluc.app.MainApplication;
import com.application.chiettinhdienluc.data.GlobalData;
import com.application.chiettinhdienluc.ui.ImageDetailActivity;
import com.application.chiettinhdienluc.ui.ImageGridActivity;

public class Utils {

	static long lastShowMess = 0;
	private static Handler mHandler = new Handler(Looper.getMainLooper());
	private static DecimalFormat formatter;
	private static String numberFormat;

	public static void showMess(boolean forceShow, final String mess) {
		try {
			if (forceShow || System.currentTimeMillis() - lastShowMess > 2000) {
				if (mess != null && mess.equals(""))
					return;

				mHandler.post(new Runnable() {

					@Override
					public void run() {
						try {
							LayoutInflater inflater = LayoutInflater.from(MainApplication.getAppContext());
							View layout = inflater.inflate(R.layout.toast_layout, null);

							TextView text = (TextView) layout.findViewById(R.id.text);
							text.setText(mess);

							Toast toast = new Toast(MainApplication.getAppContext());
							toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
							toast.setDuration(Toast.LENGTH_LONG);
							toast.setView(layout);
							toast.show();
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
				});
			}

			lastShowMess = System.currentTimeMillis();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void showMess(final String mess) {
		showMess(false, mess);
	}

	public static void showMess(final int messResId, Object... objects) {
		try {
			String str = MainApplication.getAppContext().getResources().getString(messResId, objects);
			showMess(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}	

	public static String formatDoubleNumber(Double number) {
		double roundedNumber = Math.round(number*100.0)/100.0;
		formatter = new DecimalFormat("#,###,###");
		formatter.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
		
		numberFormat = formatter.format(roundedNumber);
		return numberFormat;
	}
	public static String formatLongNumber(Long number) {
		formatter = new DecimalFormat("#,###,###");
		formatter.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
		numberFormat = formatter.format(number);
		return numberFormat;
	}

	public static double removeCommaFromMoney(String str){
		String removedComma = str.replace(",", "");
		double result;
		if (removedComma != "0")
			result = Double.parseDouble(removedComma);
		else
			result = 0;

		return result;
	}

	public static String convertSignToNoSign(String org){
		char arrChar[] = org.toCharArray();
		char result[] = new char[arrChar.length];
		for (int i = 0; i < arrChar.length; i++) {
			switch(arrChar[i]){
			case '\u00E1':
			case '\u00E0':
			case '\u1EA3':
			case '\u00E3':
			case '\u1EA1':
			case '\u0103':
			case '\u1EAF':
			case '\u1EB1':
			case '\u1EB3':
			case '\u1EB5':
			case '\u1EB7':
			case '\u00E2':
			case '\u1EA5':
			case '\u1EA7':
			case '\u1EA9':
			case '\u1EAB':
			case '\u1EAD':
			case '\u0203':
			case '\u01CE':
			{
				result[i] = 'a';
				break;
			}
			case '\u00E9':
			case '\u00E8':
			case '\u1EBB':
			case '\u1EBD':
			case '\u1EB9':
			case '\u00EA':
			case '\u1EBF':
			case '\u1EC1':
			case '\u1EC3':
			case '\u1EC5':
			case '\u1EC7':
			case '\u0207':
			{
				result[i] = 'e';
				break;
			}
			case '\u00ED':
			case '\u00EC':
			case '\u1EC9':
			case '\u0129':
			case '\u1ECB':
			{
				result[i] = 'i';
				break;
			}
			case '\u00F3':
			case '\u00F2':
			case '\u1ECF':
			case '\u00F5':
			case '\u1ECD':
			case '\u00F4':
			case '\u1ED1':
			case '\u1ED3':
			case '\u1ED5':
			case '\u1ED7':
			case '\u1ED9':
			case '\u01A1':
			case '\u1EDB':
			case '\u1EDD':
			case '\u1EDF':
			case '\u1EE1':
			case '\u1EE3':
			case '\u020F':
			{
				result[i] = 'o';
				break;
			}
			case '\u00FA':
			case '\u00F9':
			case '\u1EE7':
			case '\u0169':
			case '\u1EE5':
			case '\u01B0':
			case '\u1EE9':
			case '\u1EEB':
			case '\u1EED':
			case '\u1EEF':
			case '\u1EF1':
			{
				result[i] = 'u';
				break;
			}
			case '\u00FD':
			case '\u1EF3':
			case '\u1EF7':
			case '\u1EF9':
			case '\u1EF5':
			{
				result[i] = 'y';
				break;
			}
			case '\u0111':
			{
				result[i] = 'd';
				break;
			}
			case '\u00C1':
			case '\u00C0':
			case '\u1EA2':
			case '\u00C3':
			case '\u1EA0':
			case '\u0102':
			case '\u1EAE':
			case '\u1EB0':
			case '\u1EB2':
			case '\u1EB4':
			case '\u1EB6':
			case '\u00C2':
			case '\u1EA4':
			case '\u1EA6':
			case '\u1EA8':
			case '\u1EAA':
			case '\u1EAC':
			case '\u0202':
			case '\u01CD':
			{
				result[i] = 'A';
				break;
			}
			case '\u00C9':
			case '\u00C8':
			case '\u1EBA':
			case '\u1EBC':
			case '\u1EB8':
			case '\u00CA':
			case '\u1EBE':
			case '\u1EC0':
			case '\u1EC2':
			case '\u1EC4':
			case '\u1EC6':
			case '\u0206':
			{
				result[i] = 'E';
				break;
			}
			case '\u00CD':
			case '\u00CC':
			case '\u1EC8':
			case '\u0128':
			case '\u1ECA':
			{
				result[i] = 'I';
				break;
			}
			case '\u00D3':
			case '\u00D2':
			case '\u1ECE':
			case '\u00D5':
			case '\u1ECC':
			case '\u00D4':
			case '\u1ED0':
			case '\u1ED2':
			case '\u1ED4':
			case '\u1ED6':
			case '\u1ED8':
			case '\u01A0':
			case '\u1EDA':
			case '\u1EDC':
			case '\u1EDE':
			case '\u1EE0':
			case '\u1EE2':
			case '\u020E':
			{
				result[i] = 'O';
				break;
			}
			case '\u00DA':
			case '\u00D9':
			case '\u1EE6':
			case '\u0168':
			case '\u1EE4':
			case '\u01AF':
			case '\u1EE8':
			case '\u1EEA':
			case '\u1EEC':
			case '\u1EEE':
			case '\u1EF0':
			{
				result[i] = 'U';
				break;
			}

			case '\u00DD':
			case '\u1EF2':
			case '\u1EF6':
			case '\u1EF8':
			case '\u1EF4':
			{
				result[i] = 'Y';
				break;
			}
			case '\u0110':
			case '\u00D0':
			case '\u0089':
			{
				result[i] = 'D';
				break;
			}
			default:
				result[i] = arrChar[i];
			}
		}
		return new String(result).toLowerCase();
	}
	
	private Utils() {};


    @TargetApi(VERSION_CODES.HONEYCOMB)
    public static void enableStrictMode() {
        if (Utils.hasGingerbread()) {
            StrictMode.ThreadPolicy.Builder threadPolicyBuilder =
                    new StrictMode.ThreadPolicy.Builder()
                            .detectAll()
                            .penaltyLog();
            StrictMode.VmPolicy.Builder vmPolicyBuilder =
                    new StrictMode.VmPolicy.Builder()
                            .detectAll()
                            .penaltyLog();

            if (Utils.hasHoneycomb()) {
                threadPolicyBuilder.penaltyFlashScreen();
                vmPolicyBuilder
                        .setClassInstanceLimit(ImageGridActivity.class, 1)
                        .setClassInstanceLimit(ImageDetailActivity.class, 1);
            }
            StrictMode.setThreadPolicy(threadPolicyBuilder.build());
            StrictMode.setVmPolicy(vmPolicyBuilder.build());
        }
    }

    public static boolean hasFroyo() {
        // Can use static final constants like FROYO, declared in later versions
        // of the OS since they are inlined at compile time. This is guaranteed behavior.
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
    }

    public static boolean hasGingerbread() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
    }

    public static boolean hasHoneycomb() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
    }

    public static boolean hasHoneycombMR1() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
    }

    public static boolean hasJellyBean() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
    }

    public static boolean hasKitKat() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    }
    
    public static boolean sdCardMounted()
	{
		try
		{
			if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) 
			{
				return true;
			}
			Utils.showMess(MainApplication.getAppContext().getResources().getString(R.string.error_sdcard));			
		}
		catch(Exception e){}		
		return false;
	}
 
    public static String getFilenamePart(String s)
    {
        return (new StringBuilder()).append(s).append(".jpg").toString();
    }

    public static String getImagePath(String folder, String s)
    {
    	String path = GlobalData.sdcardPath + "/ChietTinh/" + folder;
        return (new StringBuilder()).append(path).append('/').append(getFilenamePart(s)).toString();
    }
    
    public static File getPhotoOutputMediaFile(String folder)
    {
        return new File(Utils.getImagePath(folder, Utils.createJpegName(System.currentTimeMillis())));
    }
    
    public static class ImageFileNamer
    {
        private SimpleDateFormat mFormat;
        private long mLastDate;
        private int mSameSecondCount;

        public ImageFileNamer(String s)
        {
            mFormat = new SimpleDateFormat(s);
        }
        
        public String generateName(long dateTaken)
        {
            Date date = new Date(dateTaken);
            String result = mFormat.format(date);
            
            // If the last name was generated for the same second,
            // we append _1, _2, etc to the name.            
            if(dateTaken / 1000 == mLastDate / 1000)
            {
                mSameSecondCount ++;
                result = (new StringBuilder()).append(result).append("_").append(mSameSecondCount).toString();
            } 
            else
            {
                mLastDate = dateTaken;
                mSameSecondCount = 0;
            }
            return result;
        }
    }
    
    public static String createJpegName(long dateTaken) {
    	ImageFileNamer sImageFileNamer = new ImageFileNamer(MainApplication.getAppContext().getString(R.string.image_file_name_format));
    	return sImageFileNamer.generateName(dateTaken);
    }
    
    public static void openSystemCamera(Activity activity, int requestCode, File photoFile)
    {
        activity.startActivityForResult(prepareIntent(photoFile), requestCode);
    }

    public static void openSystemCamera(Fragment fragment, int requestCode, File photoFile)
    {
        fragment.startActivityForResult(prepareIntent(photoFile), requestCode);
    }
    
	private static Intent prepareIntent(File photoFile)
    {
        Intent intent;
        try
        {
            photoFile.getParentFile().mkdirs();
            photoFile.createNewFile();
            Runtime.getRuntime().exec((new StringBuilder()).append("chmod 0666").append(photoFile.getPath()).toString());
        }
        catch(IOException ioexception)
        {
        }
        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
        return intent;
    }
	
	private static int sampleSize(int width, int target){

		int result = 1;

		for(int i = 0; i < 10; i++){

			if(width < target * 2){
				break;
			}

			width = width / 2;
			result = result * 2;

		}

		return result;
	}
	
	public synchronized static BitmapFactory.Options getResampling(int cx, int cy, int max) {
		float scaleVal = 1.0f;
		BitmapFactory.Options bfo = new BitmapFactory.Options();
		if (cx > cy) {
			scaleVal = (float) max / (float) cx;
		} else if (cy > cx) {
			scaleVal = (float) max / (float) cy;
		} else {
			scaleVal = (float) max / (float) cx;
		}
		bfo.outWidth = (int) (cx * scaleVal + 0.5f);
		bfo.outHeight = (int) (cy * scaleVal + 0.5f);
		//bfo.inDither = false;                     //Disable Dithering mode
		//bfo.inPurgeable = true;                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared
		//bfo.inInputShareable = true;              //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
		//bfo.inTempStorage = new byte[32 * 1024]; 
		return bfo;
	}

//	public synchronized static Bitmap resampleImageWithMatrix(String path, int maxDim, boolean dither)
//			throws Exception, OutOfMemoryError {
//
//		BitmapFactory.Options bfo = new BitmapFactory.Options();
//		bfo.inJustDecodeBounds = true;
//		BitmapFactory.decodeFile(path, bfo);
//
//		int dim = bfo.outWidth;        
//		dim = Math.max(dim, bfo.outHeight);
//		int ssize = sampleSize(dim, maxDim);
//
//		BitmapFactory.Options optsDownSample = new BitmapFactory.Options();		
//		optsDownSample.inSampleSize = ssize;
//
//		Bitmap bmpt = null;
//		try{
//			bmpt = BitmapFactory.decodeFile(path, optsDownSample);			
//
//			if (bmpt.getWidth() > maxDim || bmpt.getHeight() > maxDim)
//			{
//
//				Matrix m = new Matrix();
//
//				BitmapFactory.Options optsScale = getResampling(bmpt.getWidth(),
//						bmpt.getHeight(), maxDim);
//				m.postScale((float) optsScale.outWidth / (float) bmpt.getWidth(),
//						(float) optsScale.outHeight / (float) bmpt.getHeight());
//
//				int sdk = new Integer(Build.VERSION.SDK).intValue();
//				if (sdk > 4) {
//					int rotation = ExifUtils.getExifRotation(path);
//					if (rotation != 0) {
//						m.postRotate(rotation);
//					}
//				}
//
//				bmpt =  Bitmap.createBitmap(bmpt, 0, 0, bmpt.getWidth(),
//						bmpt.getHeight(), m, true);
//			}			
//		}catch(OutOfMemoryError e){
//			e.printStackTrace();
//			bmpt = null;
//			throw e;
//		}
//		catch(Exception e)
//		{			
//			e.printStackTrace();
//			bmpt = null;
//			throw e;
//		}
//		return bmpt;
//
//	}
	
	public static String getMediaPath(Activity mActivity, Uri uri) {
		try
		{
			String[] projection = { MediaStore.Images.Media.DATA };
			Cursor cursor = mActivity.managedQuery(uri, projection, null, null, null);
			if(cursor != null)
			{
				int column_index = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				return cursor.getString(column_index);
			}           
			return uri.getPath();
		}
		catch(Exception ex)
		{           
		}      
		return "";      
	}
	
	public static int checkCamera()
	{
		int cameraId = -1;
		// do we have a camera?
		if (!MainApplication.getAppContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
			Utils.showMess("No camera on this device");
		} else {
			cameraId = findFrontFacingCamera();
			if (cameraId < 0) {
				Utils.showMess("No front facing camera found.");
			}
			//	      else {
			//	        camera = Camera.open(cameraId);
			//	      }
		}

		return cameraId;
	}

	public static int findFrontFacingCamera() {
		int cameraId = -1;
		// Search for the front facing camera
		int numberOfCameras = Camera.getNumberOfCameras();
		for (int i = 0; i < numberOfCameras; i++) {
			CameraInfo info = new CameraInfo();
			Camera.getCameraInfo(i, info);
			if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
				cameraId = i;
				break;
			}
		}
		return cameraId;
	}

}	    